package com.changgou.seckill.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.pay.feign.WeiXinPayFeign;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.pojo.SeckillStatus;
import com.changgou.seckill.service.SeckillOrderService;
import entity.RedisConfig;
import entity.Result;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = {"${mq.delay.queue.seckillorder}"})
public class DelayMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SeckillOrderService seckillOrderService;
    @Autowired
    private WeiXinPayFeign weiXinPayFeign;

    /****
     * 监听消息
     * @param msg
     */
    @RabbitHandler
    public void consumeMessage(@Payload String msg) throws Exception {
        RedisConfig.convertRedisTemplate(redisTemplate);

        //读取消息
        SeckillStatus seckillStatus = JSON.parseObject(msg, SeckillStatus.class);
        //读取用户订单信息
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.boundHashOps("SeckillOrder").get(seckillStatus.getUsername());
        if (seckillOrder == null || !seckillOrder.getId().equals(seckillStatus.getOrderId())) {
            //说明订单已经被支付，直接返回
            return;
        }

        //关闭支付
        Result result = weiXinPayFeign.closePay(seckillStatus.getOrderId());
        Map<String, String> resultMap = (Map<String, String>) result.getData();

        if (resultMap != null && resultMap.get("return_code").equalsIgnoreCase("success") &&
                resultMap.get("result_code").equalsIgnoreCase("success")) {
            //支付关闭成功则取消订单
            seckillOrderService.deleteOrder(seckillStatus.getUsername());
        }
    }
}
